{
  "cells": [
    {
      "cell_type": "raw",
      "id": "1957f5cb",
      "metadata": {
        "vscode": {
          "languageId": "raw"
        }
      },
      "source": [
        "---\n",
        "sidebar_label: Redis\n",
        "sidebar_class_name: node-only\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ef1f0986",
      "metadata": {},
      "source": [
        "# RedisVectorStore\n",
        "\n",
        "```{=mdx}\n",
        ":::tip Compatibility\n",
        "Only available on Node.js.\n",
        ":::\n",
        "```\n",
        "\n",
        "[Redis](https://redis.io/) is a fast open source, in-memory data store. As part of the [Redis Stack](https://redis.io/docs/latest/operate/oss_and_stack/install/install-stack/), [RediSearch](https://redis.io/docs/latest/develop/interact/search-and-query/) is the module that enables vector similarity semantic search, as well as many other types of searching.\n",
        "\n",
        "This guide provides a quick overview for getting started with Redis [vector stores](/docs/concepts/#vectorstores). For detailed documentation of all `RedisVectorStore` features and configurations head to the [API reference](https://api.js.langchain.com/classes/langchain_redis.RedisVectorStore.html)."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c824838d",
      "metadata": {},
      "source": [
        "## Overview\n",
        "\n",
        "### Integration details\n",
        "\n",
        "| Class | Package | [PY support](https://python.langchain.com/docs/integrations/vectorstores/redis/) |  Package latest |\n",
        "| :--- | :--- | :---: | :---: |\n",
        "| [`RedisVectorStore`](https://api.js.langchain.com/classes/langchain_redis.RedisVectorStore.html) | [`@langchain/redis`](https://npmjs.com/@langchain/redis/) | ✅ |  ![NPM - Version](https://img.shields.io/npm/v/@langchain/redis?style=flat-square&label=%20&) |"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "36fdc060",
      "metadata": {},
      "source": [
        "## Setup\n",
        "\n",
        "To use Redis vector stores, you'll need to set up a Redis instance and install the `@langchain/redis` integration package. You can also install the [`node-redis`](https://github.com/redis/node-redis) package to initialize the vector store with a specific client instance.\n",
        "\n",
        "This guide will also use [OpenAI embeddings](/docs/integrations/text_embedding/openai), which require you to install the `@langchain/openai` integration package. You can also use [other supported embeddings models](/docs/integrations/text_embedding) if you wish.\n",
        "\n",
        "```{=mdx}\n",
        "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n",
        "import Npm2Yarn from \"@theme/Npm2Yarn\";\n",
        "\n",
        "<IntegrationInstallTooltip></IntegrationInstallTooltip>\n",
        "\n",
        "<Npm2Yarn>\n",
        "  @langchain/redis @langchain/core redis @langchain/openai\n",
        "</Npm2Yarn>\n",
        "```\n",
        "\n",
        "You can set up a Redis instance locally with Docker by following [these instructions](https://redis.io/docs/latest/operate/oss_and_stack/install/install-stack/docker/#redisredis-stack).\n",
        "\n",
        "### Credentials\n",
        "\n",
        "Once you've set up an instance, set the `REDIS_URL` environment variable:\n",
        "\n",
        "```typescript\n",
        "process.env.REDIS_URL = \"your-redis-url\"\n",
        "```\n",
        "\n",
        "If you are using OpenAI embeddings for this guide, you'll need to set your OpenAI key as well:\n",
        "\n",
        "```typescript\n",
        "process.env.OPENAI_API_KEY = \"YOUR_API_KEY\";\n",
        "```\n",
        "\n",
        "If you want to get automated tracing of your model calls you can also set your [LangSmith](https://docs.smith.langchain.com/) API key by uncommenting below:\n",
        "\n",
        "```typescript\n",
        "// process.env.LANGSMITH_TRACING=\"true\"\n",
        "// process.env.LANGSMITH_API_KEY=\"your-api-key\"\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "93df377e",
      "metadata": {},
      "source": [
        "## Instantiation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "dc37144c-208d-4ab3-9f3a-0407a69fe052",
      "metadata": {
        "tags": []
      },
      "outputs": [],
      "source": [
        "import { RedisVectorStore } from \"@langchain/redis\";\n",
        "import { OpenAIEmbeddings } from \"@langchain/openai\";\n",
        "\n",
        "import { createClient } from \"redis\";\n",
        "\n",
        "const embeddings = new OpenAIEmbeddings({\n",
        "  model: \"text-embedding-3-small\",\n",
        "});\n",
        "\n",
        "const client = createClient({\n",
        "  url: process.env.REDIS_URL ?? \"redis://localhost:6379\",\n",
        "});\n",
        "await client.connect();\n",
        "\n",
        "const vectorStore = new RedisVectorStore(embeddings, {\n",
        "  redisClient: client,\n",
        "  indexName: \"langchainjs-testing\",\n",
        "});"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ac6071d4",
      "metadata": {},
      "source": [
        "## Manage vector store\n",
        "\n",
        "### Add items to vector store"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "17f5efc0",
      "metadata": {},
      "outputs": [],
      "source": [
        "import type { Document } from \"@langchain/core/documents\";\n",
        "\n",
        "const document1: Document = {\n",
        "  pageContent: \"The powerhouse of the cell is the mitochondria\",\n",
        "  metadata: { type: \"example\" }\n",
        "};\n",
        "\n",
        "const document2: Document = {\n",
        "  pageContent: \"Buildings are made out of brick\",\n",
        "  metadata: { type: \"example\" }\n",
        "};\n",
        "\n",
        "const document3: Document = {\n",
        "  pageContent: \"Mitochondria are made out of lipids\",\n",
        "  metadata: { type: \"example\" }\n",
        "};\n",
        "\n",
        "const document4: Document = {\n",
        "  pageContent: \"The 2024 Olympics are in Paris\",\n",
        "  metadata: { type: \"example\" }\n",
        "}\n",
        "\n",
        "const documents = [document1, document2, document3, document4];\n",
        "\n",
        "await vectorStore.addDocuments(documents);"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "dcf1b905",
      "metadata": {},
      "source": [
        "Top-level document ids are currently not supported, but you can delete documents by providing their IDs directly to the vector store."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c3620501",
      "metadata": {},
      "source": [
        "## Query vector store\n",
        "\n",
        "Once your vector store has been created and the relevant documents have been added you will most likely wish to query it during the running of your chain or agent. \n",
        "\n",
        "### Query directly\n",
        "\n",
        "Performing a simple similarity search can be done as follows:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "aa0a16fa",
      "metadata": {},
      "outputs": [],
      "source": [
        "const similaritySearchResults = await vectorStore.similaritySearch(\"biology\", 2);\n",
        "\n",
        "for (const doc of similaritySearchResults) {\n",
        "  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3ed9d733",
      "metadata": {},
      "source": [
        "Filtering will currently look for any metadata key containing the provided string.\n",
        "\n",
        "If you want to execute a similarity search and receive the corresponding scores you can run:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "5efd2eaa",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "* [SIM=0.835] The powerhouse of the cell is the mitochondria [{\"type\":\"example\"}]\n",
            "* [SIM=0.852] Mitochondria are made out of lipids [{\"type\":\"example\"}]\n"
          ]
        }
      ],
      "source": [
        "const similaritySearchWithScoreResults = await vectorStore.similaritySearchWithScore(\"biology\", 2)\n",
        "\n",
        "for (const [doc, score] of similaritySearchWithScoreResults) {\n",
        "  console.log(`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`);\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0c235cdc",
      "metadata": {},
      "source": [
        "### Query by turning into retriever\n",
        "\n",
        "You can also transform the vector store into a [retriever](/docs/concepts/retrievers) for easier usage in your chains. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "f3460093",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "  Document {\n",
            "    pageContent: 'The powerhouse of the cell is the mitochondria',\n",
            "    metadata: { type: 'example' },\n",
            "    id: undefined\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: 'Mitochondria are made out of lipids',\n",
            "    metadata: { type: 'example' },\n",
            "    id: undefined\n",
            "  }\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "const retriever = vectorStore.asRetriever({\n",
        "  k: 2,\n",
        "});\n",
        "await retriever.invoke(\"biology\");"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e2e0a211",
      "metadata": {},
      "source": [
        "### Usage for retrieval-augmented generation\n",
        "\n",
        "For guides on how to use this vector store for retrieval-augmented generation (RAG), see the following sections:\n",
        "\n",
        "- [Tutorials: working with external knowledge](/docs/tutorials/#working-with-external-knowledge).\n",
        "- [How-to: Question and answer with RAG](/docs/how_to/#qa-with-rag)\n",
        "- [Retrieval conceptual docs](/docs/concepts/retrieval)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "069f1b5f",
      "metadata": {},
      "source": [
        "## Deleting documents\n",
        "\n",
        "You can delete documents from the vector store in two ways:\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "dde32a56",
      "metadata": {},
      "source": [
        "### Delete all documents\n",
        "\n",
        "You can delete an entire index and all its documents with the following command:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "f71ce986",
      "metadata": {},
      "outputs": [],
      "source": [
        "await vectorStore.delete({ deleteAll: true });"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b77fa077",
      "metadata": {},
      "source": [
        "### Delete specific documents by ID\n",
        "\n",
        "You can also delete specific documents by providing their IDs. Note that the configured key prefix will be automatically added to the IDs you provide:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "cb7a85ee",
      "metadata": {},
      "outputs": [],
      "source": [
        "// The key prefix will be automatically added to each ID\n",
        "await vectorStore.delete({ ids: [\"doc1\", \"doc2\", \"doc3\"] });\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "bf2357b3",
      "metadata": {},
      "source": [
        "## Closing connections\n",
        "\n",
        "Make sure you close the client connection when you are finished to avoid excessive resource consumption:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "48a98cba",
      "metadata": {},
      "outputs": [],
      "source": [
        "await client.disconnect();"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8a27244f",
      "metadata": {},
      "source": [
        "## API reference\n",
        "\n",
        "For detailed documentation of all `RedisVectorSearch` features and configurations head to the [API reference](https://api.js.langchain.com/classes/langchain_redis.RedisVectorStore.html)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "TypeScript",
      "language": "typescript",
      "name": "tslab"
    },
    "language_info": {
      "codemirror_mode": {
        "mode": "typescript",
        "name": "javascript",
        "typescript": true
      },
      "file_extension": ".ts",
      "mimetype": "text/typescript",
      "name": "typescript",
      "version": "3.7.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}